package net.bwie.vehicle.dws.job;

import com.alibaba.fastjson.JSON;
import net.bwie.realtime.guanjuntao.util.DateTimeUtil;
import net.bwie.realtime.guanjuntao.util.JdbcUtil;
import net.bwie.realtime.guanjuntao.util.KafkaUtil;
import net.bwie.vehicle.dws.bean.CarBean;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * 实时处理车辆窗口状态的主类
 */
public class VehicleWindowRealtimeStatus {
    /**
     * 主函数入口
     *
     * @param args 命令行参数
     * @throws Exception 当Flink作业执行出现异常时抛出
     */
    public static void main(String[] args) throws Exception {
        // 获取Flink执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 设置并行度为1
        env.setParallelism(1);
        // 从Kafka中消费车辆数据
        DataStream<String> kafkaStream = KafkaUtil.consumerKafka(env, "car-vehicle-data");
        // 打印原始Kafka流数据
        kafkaStream.print();
        // 调用处理函数对Kafka流进行处理
        Processheadel(kafkaStream);

        // 执行Flink作业
        env.execute("VehicleWindowRealtimeStatus");
    }

    /**
     * 处理车辆数据流
     *
     * @param kafkaStream 从Kafka中消费的车辆数据流
     */
    private static void Processheadel(DataStream<String> kafkaStream) {
        // 将Kafka流中的数据转换为CarBean对象
        SingleOutputStreamOperator<CarBean> VehicleDataMap = kafkaStream.map(
                o -> JSON.parseObject(o, CarBean.class)
        );
        // 为CarBean对象分配时间戳和水印
        SingleOutputStreamOperator<CarBean> vehicleDataSingleOutputStreamOperator = VehicleDataMap.assignTimestampsAndWatermarks(WatermarkStrategy
                .<CarBean>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                .withTimestampAssigner(
                        new SerializableTimestampAssigner<CarBean>() {
                            @Override
                            public long extractTimestamp(CarBean element, long recordTimestamp) {
                                // 从CarBean对象中提取时间戳
                                return element.getTimestamp();
                            }
                        }
                )
        );
        // 按照CarBean对象进行键控
        KeyedStream<CarBean, CarBean> vehicleDataVehicleDataKeyedStream = vehicleDataSingleOutputStreamOperator.keyBy(o -> o);
        // 定义一个基于事件时间的滚动窗口
        WindowedStream<CarBean, CarBean, TimeWindow> window = vehicleDataVehicleDataKeyedStream.window(
                TumblingEventTimeWindows.of(Time.seconds(1))
        );
        // 应用窗口函数处理数据
        SingleOutputStreamOperator<String> process = window.apply(
                new WindowFunction<CarBean, String, CarBean, TimeWindow>() {
                    @Override
                    public void apply(CarBean vehicleData, TimeWindow window, Iterable<CarBean> input, Collector<String> out) throws Exception {
                        // 将窗口的开始和结束时间格式化为字符串
                        String window_start = DateTimeUtil.convertLongToString(window.getStart(), DateTimeUtil.DATE_TIME_FORMAT);
                        String window_end = DateTimeUtil.convertLongToString(window.getStart(), DateTimeUtil.DATE_TIME_FORMAT);
                        // 构造输出字符串
                        out.collect(window_start + "," +
                                window_end + "," +
                                vehicleData.getVin() + "," +
                                vehicleData.getSpeed() + "," +
                                vehicleData.getBatteryLevel() + "," +
                                vehicleData.getBatteryTemp() + "," +
                                vehicleData.getMotorTemp() + "," +
                                vehicleData.getChargingStatus() + "," +
                                vehicleData.getEnergyConsumption());
                    }
                }
        );
        // 将处理结果写入ClickHouse数据库
        JdbcUtil.sinkToClickhouseUpsert(process, "INSERT INTO new_car.vehicle_status (window_start, window_end, vin, speed, batteryLevel, batteryTemp, motorTemp,\n" +
                "                                        chargingStatus,\n" +
                "                                        energyConsumption)\n" +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
    }
}
